package com.bitcat.mediademo;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {


    MediaPlayer mediaPlayer;

    String url = "http://192.168.1.11:8080/media/snow.mp3";
    String videoUrl = "http://192.168.1.11:8080/media/banner.mp4";

    boolean isPrepared = false;

    SoundPool soundPool;

    StandardGSYVideoPlayer gsyPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
//        mediaPlayer = MediaPlayer.create(this,R.raw.snow);

        mediaPlayer = new MediaPlayer();

        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC,0);


        gsyPlayer = findViewById(R.id.gsyPlayer);
        gsyPlayer.setUp(videoUrl,true,"安卓轮播图");
    }


    //播放音频
    public void playMusic(View view) {
//        mediaPlayer.start();

        if (isPrepared){
            mediaPlayer.start();
            return;
        }

        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    isPrepared = true;
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //暂停播放音频
    public void pauseMusic(View view) {
        mediaPlayer.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void soundPoolPlay(View view) {
        //加载音频
        int soundId = soundPool.load(this, R.raw.shoot_dan, 1);
        //监听加载完成
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                soundPool.play(soundId,1F,1F,1,0,1);
            }
        });

    }
}